package summer.codegenerator.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import summer.codegenerator.Constant;
import summer.codegenerator.dto.LoginModel;
import summer.codegenerator.dto.Result;
import summer.codegenerator.common.util.CookieUtil;
import summer.codegenerator.common.util.TokenUtil;
import summer.codegenerator.dto.ResultFactory;

/**
 * 登录相关代码
 * 
 * 
 * @author 蒋振
 * @since 2019年6月28日 下午4:58:58
 */
@Controller
@RequestMapping("/authenticate")
@ResponseBody
public class AuthenticateController {

	@RequestMapping("/login")
	public void login(@RequestBody LoginModel loginModel, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");

		String result = ResultFactory.ERROR;
		String username = loginModel.getUsername();
		String password = loginModel.getPassword();
		if (StringUtils.isNoneEmpty(username, password)) {
			if (Objects.equals("admin", username) && Objects.equals("123456", password)) {
				// 生成令牌并存入到cookie中
				String token = TokenUtil.generateToken(username);
				CookieUtil.setCookie(response, Constant.TOKEN_KEY, token, Constant.COOKIE_MAX_AGE);
				result = ResultFactory.OK;
			}
		}
		PrintWriter out = response.getWriter();
		out.append(result);
		out.close();
	}

	@RequestMapping("/logout")
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		CookieUtil.deleteCookieByName(request, response,  Constant.TOKEN_KEY);
	}
}
